package com.btkjgc.controller;

//import com.sdicons.json.model.JSONArray;

import com.btkjgc.framework.BasicController;
import com.btkjgc.model.Form;
import com.btkjgc.model.SearchForm;
import com.btkjgc.model.UpdateForm;
import com.btkjgc.models.LeftMenu;
import com.btkjgc.service.impl.LeftBarManager_Impl;
import com.btkjgc.service.intf.LeftBarManager_Intf;
import com.btkjgc.utils.HibernateUtil;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.util.*;

@Controller
public class LeftMenuRoleManageController extends BasicController {
	static Logger logger = Logger.getLogger(LeftMenuRoleManageController.class);

	private LeftBarManager_Intf leftMenuService = new LeftBarManager_Impl();

	public static Map<Integer, Integer> menuFunctionMap = null;

	public static class EntitySearchForm extends SearchForm {
		Integer roleId;

		public Integer getRoleId() {
			return roleId;
		}

		public void setRoleId(Integer roleId) {
			this.roleId = roleId;
		}
	}

	public static class LeftMenuInsertForm extends Form {
		Integer parentIndex;

		String menuText;

		String parentText;

		String url;

		Integer level;

		String icon;

		Integer minRoleLevel;

		public Integer getParentIndex() {
			return parentIndex;
		}

		public void setParentIndex(Integer parentIndex) {
			this.parentIndex = parentIndex;
		}

		public String getMenuText() {
			return menuText;
		}

		public void setMenuText(String menuText) {
			this.menuText = menuText;
		}

		public String getParentText() {
			return parentText;
		}

		public void setParentText(String parentText) {
			this.parentText = parentText;
		}

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		public Integer getLevel() {
			return level;
		}

		public void setLevel(Integer level) {
			this.level = level;
		}

		public String getIcon() {
			return icon;
		}

		public void setIcon(String icon) {
			this.icon = icon;
		}

		public Integer getMinRoleLevel() {
			return minRoleLevel;
		}

		public void setMinRoleLevel(Integer minRoleLevel) {
			this.minRoleLevel = minRoleLevel;
		}
	}

	public static class LeftMenuUpdateForm extends UpdateForm {
		String newLeftMenu;

		public String getNewLeftMenu() {
			return newLeftMenu;
		}

		public void setNewLeftMenu(String newLeftMenu) {
			this.newLeftMenu = newLeftMenu;
		}// 更新菜单
	}

	@RequestMapping(value = "left_menu_role_manage", method = {
			RequestMethod.GET, RequestMethod.POST })
	public ModelAndView process(HttpServletRequest request) {
		ModelAndView mv = super.process(request);
		request.getSession().setAttribute("test", "test1");
		// String newLeftMenu = request.getParameter("newLeftMenu");
		// mv.addObject("newLeftMenu", newLeftMenu==null?"":newLeftMenu);
		return mv;
	}

	public void list(HttpServletRequest request, ModelAndView mv,
			EntitySearchForm form) {
		mv.setViewName("left_menu_role_manage");
		String postaction = request.getParameter("postaction");
		if (postaction != null && postaction.equals("edit")) {
			String id = request.getParameter("editId");
			String url = request.getParameter("editUrl");
			String text = request.getParameter("editMenuText");
			String oldUrl = request.getParameter("oldUrl");
			leftMenuService.updateLeftMenu(id, oldUrl, url, text);
		}

		List<LeftMenu> rawLeftMenuList = leftMenuService.getRawLeftMenu();
		List<LeftMenu> roleLeftMenuList = (new LeftBarManager_Impl())
				.getLeftMenuByRoleId(form.getRoleId() != null ? form
						.getRoleId() : 5);

		// 记录哪些menu是该role显示的
		Map<Integer, Boolean> roleApprovedMap = new HashMap<Integer, Boolean>();
		for (LeftMenu leftMenu : roleLeftMenuList) {
			roleApprovedMap.put(leftMenu.getId(), true);
			for (LeftMenu level2 : leftMenu.getSubmenus()) {
				roleApprovedMap.put(level2.getId(), true);
				for (LeftMenu level3 : level2.getSubmenus()) {
					roleApprovedMap.put(level3.getId(), true);
				}
			}
		}

		// 设置哪些需要被选中
		for (LeftMenu leftMenu : rawLeftMenuList) {
			if (roleApprovedMap.containsKey(leftMenu.getId())) {
				leftMenu.setRoleApproved(true);
				for (LeftMenu level2 : leftMenu.getSubmenus()) {
					if (roleApprovedMap.containsKey(level2.getId())) {
						level2.setRoleApproved(true);
						for (LeftMenu level3 : level2.getSubmenus()) {
							if (roleApprovedMap.containsKey(level3.getId())) {
								level3.setRoleApproved(true);
							}
						}
					}
				}
			}
		}

		mv.addObject("left_menu_list", rawLeftMenuList);// 全部的leftMenu
		// 重要！！！！当前只允许等级5的管理员修改菜单栏！！！！
		// request.getSession().setAttribute("left_menu", (new
		// LeftBarManager_Impl()).getLeftMenuByRoleId(5));// 用于等级5更新菜单显示
	}

	public void insert(HttpServletRequest request, ModelAndView mv,
			LeftMenuInsertForm form) {
		leftMenuService.insertLeftMenu(request, form.getParentIndex(),
				form.getMenuText(), form.getUrl(), form.getLevel(),
				form.getIcon(), form.getParentText(), form.getMinRoleLevel());
	}

	public void update(HttpServletRequest request, ModelAndView mv,
			LeftMenuUpdateForm form) {
		String jsonStr = form.getNewLeftMenu();
		JSONArray level1Array = new JSONArray(jsonStr);

		int index = 1;
		for (int i0 = 0; i0 < level1Array.length(); i0++) {
			JSONObject level1 = level1Array.getJSONObject(i0);
			leftMenuService.updateLeftMenu(request, level1.getInt("id"),
					index++, 0, 1);
			try {
				JSONArray level2Array = level1.getJSONArray("children");
				if (level2Array != null) {
					int parentIndex1 = index - 1;// 二级菜单的父级菜单index
					for (int i1 = 0; i1 < level2Array.length(); i1++) {
						JSONObject level2 = level2Array.getJSONObject(i1);
						leftMenuService.updateLeftMenu(request,
								level2.getInt("id"), index++, parentIndex1, 2);
						try {
							JSONArray level3Array = level2
									.getJSONArray("children");
							if (level3Array != null) {
								int parentIndex2 = index - 1;// 三级菜单的父级菜单index
								for (int i2 = 0; i2 < level3Array.length(); i2++) {
									JSONObject level3 = level3Array
											.getJSONObject(i2);
									leftMenuService.updateLeftMenu(request,
											level3.getInt("id"), index++,
											parentIndex2, 3);
								}
							}
						} catch (JSONException e) {

						}
					}
				}
			} catch (JSONException e) {

			}
		}

		// logger.info("新菜单： "+jsonStr);
		// int id = Integer.parseInt(form.getId());
		// entityService.updateEntityById(id, form.getEntityName(),
		// form.getAddress(), form.getPhone(), form.getContacts(), 0, 0.0,
		// 0.0, 0.0, 0, 0, 0, 0.0);
	}

	public void delete(HttpServletRequest request, ModelAndView mv, String id) {
		leftMenuService.deleteById(id);
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "dispose_menu", method = { RequestMethod.GET })
	public @ResponseBody
	String disposeCars(HttpServletRequest request) {
		List<String> requestList = new ArrayList<String>();// 获取的ftl传过来的参数
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1 && paramName.contains("id")) {
				String paramValue = paramValues[0];
				requestList.add(paramValue);
			}
		}

		String roleId = request.getParameter("roldId");

		String hql = "DELETE FROM RoleFunction WHERE roleid=" + roleId;
		HibernateUtil.executeUpdate(hql, null);

		if (requestList.size() > 1) {
			for (int i = 0; i < requestList.size(); i++) {
				leftMenuService.insertRoleFunction(roleId, requestList.get(i));
			}

			return '"' + "修改成功！" + '"';
		} else {
			return '"' + "该角色菜单已清空！！" + '"';
		}
		// return '"' + "修改成功！" + '"';
	}

}
